package com.ls.controller;

import com.ls.util.CommunityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author ls
 */
@RestController
public class TestController {

    private static final Logger logger = LoggerFactory.getLogger(TestController.class);

    /**
     * cookie 示例
     *
     * @param response
     * @return
     */
    @GetMapping("/cookie/set")
    public String setCookie(HttpServletResponse response) {
        // 创建cookie
        Cookie cookie = new Cookie("code", CommunityUtil.generateUUID());
        // 设置cookie的生效范围
        cookie.setPath("community/cookie");
        // 设置cookie的生存时间
        cookie.setMaxAge(60 * 10);
        // 发送cookie
        response.addCookie(cookie);
        return "set cookie";
    }

    @GetMapping("/cookie/get")
    public String getCookie(HttpServletRequest request, @CookieValue("code") String code) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            logger.info("{}: {}", cookie.getName(), cookie.getValue());
        }
        logger.info(code);
        return "get Cookie";
    }

    /**
     * session 示例
     *
     * @param session
     * @return
     */
    @GetMapping("/session/set")
    public String setSession(HttpSession session) {
        session.setAttribute("id", 1);
        session.setAttribute("name", "test");
        return "set session";
    }

    @GetMapping("/session/get")
    public String getSession(HttpSession session) {
        logger.info("id: {}", session.getAttribute("id"));
        logger.info("name: {}", session.getAttribute("name"));
        return "get session";
    }

}
